# 有多个模型，且请求/响应需要声明多个模型的时候，可以根据不同使用场景结合 typing 库里面的 Union、List 来达到目的
import uvicorn
from typing import Union, List, Dict, Optional
from fastapi import FastAPI
from pydantic import BaseModel, EmailStr

vars: Union[int, str]

vars = 123

'''
Union
联合类型

vars: Union[int, str]
# 等价于
vars: [int or str]


vars: Union[int]
# 等价于
vars: int

Union[int] 返回的也是 int 类型
Union[int] == int

重复的类型参数会自动忽略掉
Union[int, str, int] == Union[int, str]

自动忽略类型参数顺序
Union[int, str] == Union[str, int]

union 嵌套 union 会自动解包
Union[Union[int, str], float] == Union[int, str, float]

'''

app = FastAPI()


class BaseItem(BaseModel):
    desc: str
    type: str


class CarItem(BaseItem):
    type = "car"


class PlaneItem(BaseItem):
    type = 'plane'
    size: int


items = {
    "item1": {
        "desc": "All my friends drive a low rider",
        "type": "car"
    },
    "item2": {
        "desc": "Music is my aeroplane, it's my aeroplane",
        "type": "plane",
        "size": 5,
    }
}


@app.get('/items/{item_id}', response_model=Union[PlaneItem, CarItem])
async def read_item(item_id: str):  # item_id 作为键去 items 中找到对应的值
    return items[item_id]


if __name__ == '__main__':
    uvicorn.run(app='main:app', host='127.0.0.1', port=8000, reload=True, debug=True)
